package com.itheima.suanfa;

public class BinarySearch {
    public static void main(String[] args) {
        //测试
        int[] arr = {1, 2, 3, 4, 5, 6, 15, 47};
        int result = BinarySearch(arr, 15);
        System.out.println(result);
    }


    //实现二分查找
    public static int BinarySearch(int[] arr, int target) {
        int i = 0, j = arr.length - 1;
        while (i <= j) {
            int mid = (i + j) / 2; //代表索引的中间量
            if (arr[mid] < target) {
                i = mid + 1;  //目标在左边
            } else if (arr[mid] > target) {
                j = mid - 1;  //目标在右边
            } else {
                return mid;
            }
        }
        return -1;
    }
}
